<template>
  <el-dialog
    :close-on-click-modal="false"
    title="项目月成本进度计划"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <!-- <el-input v-model="form.projectName" :disabled="true" /> -->
            <el-input v-model="form.projectName" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showTargetSetListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="月份" prop="month">
            <el-date-picker
              v-model="form.month"
              type="month"
              value-format="yyyy-MM"
              :disabled="disableForm"
              placeholder="选择月"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="月计划完成金额" prop="completeAmount">
            <el-input v-model="form.completeAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <div style="padding-bottom: 10px;">
        <el-button type="primary" @click="showTargetSetListModal = true">引入计划</el-button>
        <el-button type="primary" @click="deleteDetail">删除计划</el-button>
      </div> -->
      <div class="com-form-title">本月计划说明</div>
      <el-form-item label="月计划重要节点工期" prop="importantNodeDuration">
        <el-input v-model="form.importantNodeDuration" type="textarea" :rows="4" :disabled="disableForm" />
      </el-form-item>
      <el-form-item label="开工累计完成情况" prop="cumulativeCompletion">
        <el-input v-model="form.cumulativeCompletion" type="textarea" :rows="4" :disabled="disableForm" />
      </el-form-item>
      <div class="com-form-title">本月计划明细</div>
      <com-table
        v-model="selectRow"
        :data="targetList"
        :columns="columns"
        highlight-current-row
        default-expand-all
        :no-page="true"
        height="300"
        row-key="number"
        :tree-props="{children: 'childrens', hasChildren: 'hasChildren'}"
      >
        <template v-slot:contractWorkVolume="{row}">
          <el-input v-model="row.contractWorkVolume" />
        </template>
        <template v-slot:unitPrice="{row}">
          <el-input v-model="row.unitPrice" @input="getPlanFinishAmount" />
        </template>
        <template v-slot:amount="{row}">
          <el-input v-model="row.amount" />
        </template>
        <template v-slot:drawingWorkVolume="{row}">
          <el-input v-model="row.drawingWorkVolume" />
        </template>
        <template v-slot:measuredWorkVolume="{row}">
          <el-input v-model="row.measuredWorkVolume" />
        </template>
        <template v-slot:planFinishCount="{row}">
          <el-input v-model="row.planFinishCount" @input="getPlanFinishAmount" />
        </template>
        <template v-slot:planFinishAmount="{row}">
          <el-input v-model="row.planFinishAmount" disabled />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>

      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <project-list :show-modal.sync="showTargetSetListModal" @getSelectedRows="getSelectedRows" />
  </el-dialog>
</template>

<script>
import { addProjectSchedulePlanInfo, updateProjectSchedulePlanInfo, getProjectSchedulePlanInfoDetail } from '@/api/planManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import ProjectList from '@/components/TreeModal/project3'
import moment from 'moment'
export default {
  name: 'AddProjectSchedulePlanInfo',
  components: {
    fileUploader,
    ProjectList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        projectName: '',
        month: '',
        outValue: '',
        importantNodeDuration: '',
        cumulativeCompletion: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: '',
        completeAmount: ''
      },
      columns: [
        {
          fixed: 'left',
          label: '清单编号',
          prop: 'number',
          width: '150'
        },
        {
          fixed: 'left',
          label: '清单名称',
          prop: 'name',
          width: '200'
        },
        {
          label: '清单单位',
          prop: 'unit'
        },
        {
          label: '合同工程量',
          slot: 'contractWorkVolume',
          width: '150'
        },
        {
          label: '成本单价',
          slot: 'unitPrice',
          width: '150'
        },
        // {
        //   label: '金额',
        //   slot: 'amount'
        // },
        {
          label: '计划完成数量',
          slot: 'planFinishCount',
          width: '150'
        },
        {
          label: '计划完成金额',
          slot: 'planFinishAmount',
          width: '150'
        },
        {
          label: '图纸工程量',
          slot: 'drawingWorkVolume',
          width: '150'
        },
        {
          label: '实测工程量',
          slot: 'measuredWorkVolume',
          width: '150'
        },
        {
          label: '备注',
          slot: 'remark',
          width: '150'
        }
        // {
        //   fixed: 'right',
        //   prop: 'options',
        //   slot: 'options'
        // }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        projectName: [
          { required: true, message: '项目名称', trigger: 'change' }
        ]
        // unifiedSocialCreditCode: [
        //   { required: true, message: '统一社会信用代码', trigger: 'change' }
        // ]
      },
      provinceData: [],
      cityData: [],
      total: 0
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSelectedRows(obj) {
      //
      // // 将值赋给
      // this.form = {
      //   projectName: obj.row.projName
      // }
      this.form.projectName = obj.row.projectName
      const formateData = (data) => {
        return data.map(item => {
          const { number, name, unit, childrens, parentId, contractCount, costUnitPrice, drawingWorkVolume, measuredWorkVolume } = item
          return {
            parentId,
            number,
            name,
            unit,
            ...childrens ? {
              childrens: formateData(childrens)
            } : {},
            'contractWorkVolume': contractCount,
            'unitPrice': costUnitPrice,
            'price': '',
            'amount': '',
            'drawingWorkVolume': drawingWorkVolume,
            'measuredWorkVolume': measuredWorkVolume,
            'planFinishAmount': '',
            'remark': ''
          }
        })
      }
      this.targetList = formateData(obj.list)
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getProjectSchedulePlanInfoDetail({ projectSchedulePlanInfoId: id }).then(res => {
        const { lstAttachment, lstProjectSchedulePlanDetail } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstProjectSchedulePlanDetail && lstProjectSchedulePlanDetail.length > 0) {
          this.targetList = lstProjectSchedulePlanDetail
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        const formateData = (data) => {
          return data.map(item => {
            return {
              ...item,
              id: null,
              parentId: null,
              ...item.childrens ? {
                childrens: formateData(item.childrens)
              } : {}
            }
          })
        }
        if (valid) {
          const params = {
            projectSchedulePlanInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstAttachment: this.fileList,
            lstProjectSchedulePlanDetail: formateData(this.targetList)
          }
          const fn = this.optType === 'add' ? addProjectSchedulePlanInfo : updateProjectSchedulePlanInfo

          if (this.optType === 'add') {
            params.lstProjectSchedulePlanDetail.forEach(item => {
              item.id = ''
              if (item.childrens.length > 0) {
                item.childrens.forEach(i => {
                  i.id = ''
                })
              }
            })
          }
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    // 获取计划完成金额
    getPlanFinishAmount() {
      if (this.selectRow) {
        let planFinishCount = 0
        let unitPrice = 0
        if (this.selectRow.planFinishCount) {
          planFinishCount = this.selectRow.planFinishCount
        }
        if (this.selectRow.unitPrice) {
          unitPrice = this.selectRow.unitPrice
        }
        const planFinishAmount = Number.parseFloat(unitPrice) * Number.parseFloat(planFinishCount)
        this.selectRow.planFinishAmount = planFinishAmount.toFixed(2)
      }
      // 获取完成金额
      this.getCompleteAmount()
    },
    // 获取完成
    getCompleteAmount() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.planFinishAmount) {
            sum += Number.parseFloat(item.planFinishAmount)
          }
        })
      }
      formateData(this.targetList)
      this.form.completeAmount = sum.toFixed(2)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
